from flask import Flask, request, jsonify, current_app, g, url_for, redirect, send_from_directory
import uuid
import setting, config
from SCConfig import SCConfig
# from werkzeug import secure_filename   # 获取上传文件的文件名
import os

import json
import ants
import nibabel as nib
import math

app = Flask(__name__)
app.config.from_object(setting)


data = {}



def allowed_file(filename):   # 验证上传的文件名是否符合要求，文件名必须带点并且符合允许上传的文件类型要求，两者都满足则返回 true
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in config.ALLOWED_EXTENSIONS

@app.route('/getData', methods=['GET'])
def getData():

    

    B = config.B

    client = request.args.get('client', -1, type=int)

    start = request.args.get('start', -1, type=int)

    myUuid = request.args.get('uuid', '', type=str)

    allData = request.args.get('allData', '', type=int)

    
    res = {
        "status": 0,
        "msg": "success",
        "client": client,
        "start": start,
        "over": 0,
        "data": []
    }

    if myUuid not in data.keys():

        print("uuid<%s>的数据不存在" % myUuid)

        res["status"] = 1
        res["msg"] = "uuid<%s>的数据不存在" % myUuid
        return jsonify(res)


    mysc = data[myUuid]

    mydata = mysc.data

    # print("data len %d" % len(mydata))

    # 分段传输
    if allData == 0:
        if mysc.imagesCols:
            batData = mysc.addImage(mydata[client][start:start+B])
        else:
            batData = mydata[client][start:start+B]
    else:
        if mysc.imagesCols:
            batData = mysc.addImage(mydata)
        else:
            batData = mydata
        res["over"] = 1
        res["data"] = batData
        data.pop(myUuid)
        return jsonify(res)

    res["data"] = batData

    # 如果该客户端分配数据完毕，轮到下一个客户端
    if start + B >= len(mydata[client]):
        # 不是最后一个客户端
        if res["client"] < len(mydata) - 1:
            res["client"] += 1
            res["start"] = 0
        
        # 数据传输结束
        else:
            data.pop(myUuid)
            res["over"] = 1
    else:
        res["start"] += B

    # # 数据传输结束
    # if res["client"] == len(mydata) - 1 and start + B >= len(mydata[client]):
    #     data.pop(myUuid)
    #     res["over"] = 1


    return jsonify(res)

@app.route('/dataInit', methods=['GET', 'POST'])
def dataInit():
    
    res = {
        "status": 0,
        "msg": "success",
        "uuid": "",
        "start": 0,
        "client": 0,
        "allData": 1
    }

    ini_path = ""
    if request.method == 'POST':   # 如果是 POST 请求方式
        
        file = request.files['file']   # 获取上传的文件
        if file and allowed_file(file.filename):   # 如果文件存在并且符合要求则为 true
            filename = file.filename  # 获取上传文件的文件名
            print("filename:", filename)
            ini_path = os.path.join(config.SCC_INI_PATH, filename)
            file.save(ini_path)   # 保存文件
            print('"{}" upload successed!'.format(ini_path))   # 返回保存成功的信息
        else:
            res["msg"] = "获取不到文件"
            print("获取不到文件")
    
    # return jsonify(res)
    
    B = 50
    
    myUuid = uuid.uuid4().hex

    sc = SCConfig.SCConfig(ini_path=ini_path)


    mydata = None

    try:
        mydata = sc.allocation()

        data[myUuid] = sc

        print(sc.imagesCols)

        res["uuid"] = myUuid

        # 如果有图像文件，不用一次性返回
        if sc.imagesCols:
            res["allData"] = 0

        print("data len %d" % len(mydata))


    except:

        res["msg"] = "配置文件有错，请检查后重新提交"
        res["status"] = -1

    return jsonify(res)

# 加载数据
@app.route('/baseData', methods=['GET', 'POST'])
def baseData():
    
    res = {
        "status": 0,
        "msg": "success",
        "data": {}
    }

    ini_path = ""
    if request.method == 'POST':   # 如果是 POST 请求方式
        
        file = request.files['file']   # 获取上传的文件
        if file and allowed_file(file.filename):   # 如果文件存在并且符合要求则为 true
            filename = file.filename  # 获取上传文件的文件名
            print("filename:", filename)
            ini_path = os.path.join(config.SCC_INI_PATH, filename)
            file.save(ini_path)   # 保存文件
            print('"{}" upload successed!'.format(ini_path))   # 返回保存成功的信息
        else:
            res["msg"] = "获取不到文件"
            print("获取不到文件")
    
    # return jsonify(res)


    sc = SCConfig.SCConfig(ini_path=ini_path)


    mydata = None

    try:
        mydata = sc.allocation()

        res["data"] = mydata

    except:

        res["msg"] = "配置文件有错，请检查后重新提交"
        res["status"] = -1


    return jsonify(res)



# 下载图片文件
@app.route('/downloadFile', methods=['POST'])
def downloadFile():
    
    req = request.get_data(as_text=True)

    # print(req)

    reqDist =  json.loads(req)

    # print(reqDist)

    path = reqDist["filePath"].strip()

    try:
        if not os.path.exists(path):

            return ''

        newPath = "/home/huangyunyou/crzzy/peizhuntuxiang"

        filename = path.split('/')[-1]

        # peizhun(inputPath=path, outoutPath=newPath+"/"+filename, image_type='MRI', weighting="T1")

        return send_from_directory(path[:-len(filename)], filename, as_attachment=True)  # as_attachment=True 一定要写，不然会变成打开，而不是下载

        # 返回配准后的
        # return send_from_directory(newPath, filename, as_attachment=True)  # as_attachment=True 一定要写，不然会变成打开，而不是下载


    except:

        return ''


if __name__ == '__main__':
    
    app.run(host="0.0.0.0", port=5000)